package demo.topic12.beanutils;

import bean.Dog;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;

/**
 * 1. BeanUtils.setProperty：动态设置JavaBean对象的属性值‌
 * 2. BeanUtils.copyProperties：对象属性拷贝的工具方法
 */
public class BeanUtilsDemo {
    @Test
    public void test1() {
        String name = "小黄";
        int age = 2;
        String color = "黄色";

        Dog dog = new Dog();
        try {
            // 动态设置JavaBean对象的属性值‌
            BeanUtils.setProperty(dog, "name", name);
            BeanUtils.setProperty(dog, "age", age);
            BeanUtils.setProperty(dog, "color", color);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println(dog.toString());  // Dog{name='小黄', age=2, color='黄色'}
    }

    @Test
    public void test2() {
        Dog dog = new Dog("小黄", 2, "黄色");
        Dog newDog = new Dog();
        try {
            // 对象属性拷贝的工具方法
            BeanUtils.copyProperties(newDog, dog);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println(newDog.toString());  // Dog{name='小黄', age=2, color='黄色'}
    }
}
